#! /usr/bin/env python
#coding=utf-8

# pylint: disable-msg=W0704

""" push commit msg to zentao """


import datetime
import time
import re
from urllib import urlopen
#import json
#from os import path
import base64
import hashlib
import os

# 作为第三方应用调用zentao接口时需要的参数; 
#	具体参见： https://www.zentao.net/book/zentaopmshelp/integration-287.html   【在第三方应用中集成禅道】
ZENTAO_CODE="devOpsRobot"
ZENTAO_KEY="cccxxxxyyyyyzzzz"
# zentao的基础路径
ZENTAO_BASE_URL="http://xxx.yy.zzz.mm/zentao"

# 针对url中存在中文时候
import sys
reload(sys)
sys.setdefaultencoding('utf8')

def run(transaction, config):
    # 只针对特定的project进行处理
    #if not "joint3.0/trans" in os.getenv("GL_PROJECT_PATH"):
    #  return("", 0)

    commitMsg = transaction.getCommitMsgWithLinesep()  # getCommitMsg
    userId = transaction.getUserID()
    reversion = transaction.getRevision()

    commitMsgBylines = commitMsg.splitlines(False)
    firstLine = commitMsgBylines[0].strip()
    # 确保提交的日志满足约定的格式, 形如:  story:123456 xxxxxx
    patt = re.compile("(story|bug|task)\:(\d+)\s.+")
    result = re.search(patt,firstLine)
    if(result == None):
      return("", 0)

    ##### 组装提交给zentao的信息
    objecType = result.group(1)
    objectID = result.group(2)
    commentMsg = commitMsg
    # 下面这行注释依然是针对中文路径, 强烈不建议svn路径中存在中文;
    #commentMsg = commentMsg.replace("{U+","\\u").replace("}", "").encode('utf8').decode('unicode_escape')    
    commentMsg = commentMsg + os.linesep + "#GIT: " + os.getenv("GL_PROJECT_PATH")
    # base64编码一下，避免http调用失败; 其中将 + 无法放在queryString部分，所以这里我们作个约定替换
    commentMsg = base64.b64encode(commentMsg).replace("+", "___")
    
    ##### invoke zentao
    # 按照zentao提供的扩展文档, 计算出本次调用时的token
    time1 = int(time.time())
    token = hashlib.md5((ZENTAO_CODE+ZENTAO_KEY+str(time1)).encode(encoding='UTF-8')).hexdigest()
    # 拼接出最终的http调用链接, 这里需要zentao扩展开发的支撑. 详见本人博客
    visitUrl = '{}/api.php?m=action&f=comment2&objectType={}&objectID={}&actionType=gitcommited&comment={}&actor={}&extra={}&code={}&time={}&token={}'.format(ZENTAO_BASE_URL, objecType, objectID,commentMsg, userId,reversion, ZENTAO_CODE, time1, token)
    # 发起调用	
    response = urlopen(visitUrl)
    # 验证调用是否成功
    if(response.read().decode("UTF-8").isdigit()):
      return ("", 0)

    return (response.read().decode("UTF-8"), 1)

  
def test():
    ##### invoke zentao
    # 按照zentao提供的扩展文档, 计算出本次调用时的token
    time1 = int(time.time())
    token = hashlib.md5((ZENTAO_CODE+ZENTAO_KEY+str(time1)).encode(encoding='UTF-8')).hexdigest()
    # 拼接出最终的http调用链接, 这里需要zentao扩展开发的支撑. 详见本人博客: https://fulizhe.blog.csdn.net/article/details/119079005
    visitUrl = '{}/api.php?m=action&f=comment2&objectType={}&objectID={}&actionType=gitcommited&comment={}&actor={}&extra={}&code={}&time={}&token={}'.format(ZENTAO_BASE_URL, objecType, objectID,commentMsg, userId,reversion, ZENTAO_CODE, time1, token)
    # 发起调用	
    response = urlopen(visitUrl)
    # 验证调用是否成功
    if(response.read().decode("UTF-8").isdigit()):
      return ("", 0)

    return (response.read().decode("UTF-8"), 1)